﻿using EMS20.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EMS20.Help
{
    using System.Drawing;
    public class Vcode : System.Web.IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(System.Web.HttpContext context)
        {
            //得到验证码
            string strVcode = GetVcode(1);

            //保存验证码
            context.Session[Kits.Vcode] = strVcode;

            //准备一张纸
            using (Image img = new Bitmap(65, 25))
            {
                //叫来画家
                using (Graphics grap = Graphics.FromImage(img))
                {
                    grap.Clear(Color.White);
                    grap.DrawRectangle(Pens.Black, 0, 0, img.Width - 1, img.Height - 1);

                    //将验证码画在纸上
                    grap.DrawString(strVcode, new Font("微软雅黑", 16, FontStyle.Italic | FontStyle.Strikeout), Brushes.Red, 0, 0);

                    img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }

        Random r = new Random();

        /// <summary>
        /// 得到验证码
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        private string GetVcode(int num)
        {
            char[] cha = new char[] { '1', '2', '3', 'a', 'b', 'c', 'A', 'B', 'C' };
            string strVcode = string.Empty;
            for (int i = 0; i < num; i++)
            {
                strVcode += cha[r.Next(0, cha.Length)];
            }
            return strVcode;
        }


    }
}
